package nickthissen.iracing.activities;

import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;

import nickthissen.iracing.common.Task;

/**
 * Created by Nick on 22-5-13.
 */
public abstract class TaskActivity extends SherlockActivity
{
    private static final String TASK_IN_PROGRESS = "TASK_IN_PROGRESS";

    protected Task<?> task;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        SherlockUtils.setNotificationBar(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.onCancelTask();
    }

    @Override
    protected void onRestoreInstanceState(Bundle state)
    {
        super.onRestoreInstanceState(state);
        this.onRestoreTask(state);
    }

    @Override
    protected void onSaveInstanceState(Bundle state)
    {
        super.onSaveInstanceState(state);
        if (this.isFinishing())
        {
            this.onSaveTask(state);
        }
    }

    protected void onCancelTask()
    {
        if (task != null && task.getStatus() == AsyncTask.Status.RUNNING)
        {
            task.cancel(true);
            task = null;
        }
    }

    private void onSaveTask(Bundle state)
    {
        final Task<?> t = task;
        if (t != null && t.getStatus() != AsyncTask.Status.FINISHED)
        {
            // Cancel running task
            t.cancel(true);

            // Store that this task was running, and store task input
            state.putBoolean(TASK_IN_PROGRESS, true);
            this.saveTaskInput(state);

            task = null;
        }
    }

    private void onRestoreTask(Bundle state)
    {
        if (state.getBoolean(TASK_IN_PROGRESS))
        {
            // A task was running, restore it
            final Object input = this.restoreTaskInput(state);

            this.runTask(input);
        }
    }

    protected void runTask(Object input)
    {
        if (task == null || task.getStatus() == AsyncTask.Status.FINISHED)
        {
            task = createTask();
            task.execute(input);
        }
        else
        {
            Log.w("TaskActivity", "Task was null or not finished.");
        }
    }

    protected abstract Task<?> createTask();
    protected abstract void saveTaskInput(Bundle state);
    protected abstract Object restoreTaskInput(Bundle state);
}
